<template>
  <div class="app-config">
    <!-- 广告图（单图） -->
    <el-card class="config-section">
      <div slot="header"><span>广告图（单图）</span></div>
      <el-form :model="adForm" label-width="80px">
        <!-- 1 上传图片 -->
        <el-form-item label="广告图">
          <image-upload v-model="adForm.url"/>
        </el-form-item>

        <!-- 2 选跳转帖子 -->
        <el-form-item label="跳转帖子">
          <el-button size="mini" @click="adPostDialog = true">选择帖子</el-button>
          <span v-if="adForm.postId" style="margin-left:10px;">
        已选帖子ID：{{ adForm.postId }}
      </span>
        </el-form-item>

        <!-- 3 提交 -->
        <el-form-item>
          <el-button type="primary" size="small" @click="submitAd">提交</el-button>
        </el-form-item>
      </el-form>

      <!-- 官方弹窗：选帖子 -->
      <el-dialog title="选择帖子" :visible.sync="adPostDialog" width="70%">
        <RichText mode="selector" @selected="onAdPostSelected"/>
      </el-dialog>
    </el-card>

    <!-- 顶部轮播图 -->
    <el-card class="config-section">
      <div slot="header"><span>顶部轮播图</span></div>
      <el-form :model="topForm" label-width="100px">
        <el-form-item label="轮播图片">
<!--          <image-upload v-model="topForm.urls" multiple/>-->
          <ImageWithPostSelector
            v-model="topForm.urls"
            :postIds="topForm.postIds"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="submitTop">提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 首页通知 -->
    <el-card class="config-section">
      <div slot="header"><span>首页通知</span></div>
      <el-form :model="noticeForm" label-width="100px">
        <el-form-item label="通知内容">
          <el-input
            v-model="noticeForm.content"
            type="textarea"
            :rows="3"
            placeholder="请输入首页通知内容"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="submitNotice">提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 活动轮播图 -->
    <!-- 活动轮播图 -->
    <!-- 活动描述文本 -->

    <el-card class="config-section">
      <el-form :model="activityDescForm" label-width="100px">
        <el-form-item label="活动描述">
          <el-input
            v-model="activityDescForm.text"
            type="textarea"
            :rows="3"
            placeholder="请输入活动轮播图的描述文本"
            maxlength="300"
            show-word-limit
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="submitActivityDesc">提交描述</el-button>
        </el-form-item>
      </el-form>
      <el-divider/>
      <div slot="header"><span>活动轮播图</span></div>

      <!-- 轮播图片 -->
      <el-form :model="activityForm" label-width="100px">
        <el-form-item label="轮播图片">
<!--          <image-upload v-model="activityForm.urls" multiple/>-->
          <ImageWithPostSelector
            v-model="activityForm.urls"
            :postIds="activityForm.postIds"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="submitActivity">提交轮播图</el-button>
        </el-form-item>
      </el-form>


    </el-card>

    <!-- 热卖轮播图 -->
    <!-- 热卖描述文本 -->
    <el-card class="config-section">
      <el-form :model="hotDescForm" label-width="100px">
        <el-form-item label="热销描述">
          <el-input
            v-model="hotDescForm.text"
            type="textarea"
            :rows="3"
            placeholder="请输入热卖描述文本"
            maxlength="300"
            show-word-limit
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="submitHotDesc">提交描述</el-button>
        </el-form-item>
      </el-form>

      <el-divider/>
      <div slot="header"><span>热卖轮播图</span></div>
      <el-form :model="hotForm" label-width="100px">
        <el-form-item label="轮播图片">
<!--          <image-upload v-model="hotForm.urls" multiple/>-->
          <ImageWithPostSelector
            v-model="hotForm.urls"
            :postIds="hotForm.postIds"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="submitHot">提交</el-button>
        </el-form-item>
      </el-form>


    </el-card>
  </div>
</template>

<script>
// 引入新 API
import { saveAppConfig, getAppConfig } from "@/api/test/test"; // 引入新接口
import ImageWithPostSelector from "@/components/banner/ImageWithPostSelector.vue"; // 引入新接口
import RichText from '@/views/app/richText/index.vue'



export default {
  name: "AppHomePageConfig",
  components: {ImageWithPostSelector, RichText},
  data() {
    return {
      adPostDialog: false, // 控制弹窗
      adForm: {url: "",postId: null},
      noticeForm: {content: ""},
      topForm: {urls: [], postId: null},
      activityForm: {urls: [],postIds: []},
      // 活动轮播图描述（文本）
      activityDescForm: {text: ""},
      hotForm: {urls: [],postIds: []},
      hotDescForm: {text: ""},
    };
  },
  created() {
    this.loadAllConfigs(); // 如果后端也提供 GET 接口，可实现加载；否则可先注释
  },
  methods: {
    // 打开帖子选择器（单图用）
    // 打开帖子选择器（单图用）
    openAdPostSelector() {
      this.$dialog({
        title: '选择帖子',
        width: '70%',
        component: () => import('@/views/app/richText/index.vue'),
        props: { mode: 'selector' },
        on: {
          selected: (id) => {
            this.adForm.postId = id;
          }
        }
      });
    },
    /* 其它方法 … */
    onAdPostSelected(id) {
      this.adForm.postId = id
      this.adPostDialog = false
    },



    async loadAllConfigs() {
      try {
        const res = await getAppConfig();
        const config = res.data || {};   // ← 这里必须是 config，别写成 c
        /* 下面全部用 config.xxxJson */
        const advArr = JSON.parse(config.homeAdJson || '[]');
        this.adForm.url    = advArr[0]?.url   || '';
        this.adForm.postId = advArr[0]?.targetId || null;

        const topArr = JSON.parse(config.homepageBannerJson || '[]');
        this.topForm.urls   = topArr.map(it => it.url);
        this.topForm.postIds= topArr.map(it => it.targetId);

        const actArr = JSON.parse(config.activityBannerJson || '[]');
        this.activityForm.urls   = actArr.map(it => it.url);
        this.activityForm.postIds= actArr.map(it => it.targetId);

        const hotArr = JSON.parse(config.hotBannerJson || '[]');
        this.hotForm.urls   = hotArr.map(it => it.url);
        this.hotForm.postIds= hotArr.map(it => it.targetId);

        this.noticeForm.content    = config.homeNotice || '';
        this.activityDescForm.text = config.activityDesc || '';
        this.hotDescForm.text      = config.hotDesc || '';
      } catch (e) {
        console.error('加载配置失败', e);
        this.$message.warning('加载配置失败，使用默认值');
      }
    },


    // 【可选】如果你有对应的 GET 接口，可以加载已有数据
    // 暂时先不实现加载，聚焦提交

    // 提交广告图（单图）
    async submitAd() {
      const payload = [
        {
          url: this.adForm.url,
          type: 'post',
          skipUrl: '',
          targetId: this.adForm.postId || ''
        }
      ];
      await this.saveConfig('homeAdJson', JSON.stringify(payload));
    },
    // 提交顶部轮播图
    async submitTop() {
      const arr = this.topForm.urls.map((url, idx) => ({
        url,
        type: 'post',
        skipUrl: '',
        targetId: this.topForm.postIds[idx] || ''
      }));
      await this.saveConfig('homepageBannerJson', JSON.stringify(arr));
    },
    // 首页通知
    async submitNotice() {
      await this.saveConfig("homeNotice", this.noticeForm.content);
    },
    // 提交活动轮播图
    async submitActivity() {
      const arr = this.activityForm.urls.map((url, idx) => ({
        url,
        type: 'post',
        skipUrl: '',
        targetId: this.activityForm.postIds[idx] || ''
      }));
      await this.saveConfig('activityBannerJson', JSON.stringify(arr));
    },
    // 提交活动轮播图描述
    async submitActivityDesc() {
      await this.saveConfig("activityDesc", this.activityDescForm.text);
    },
    // 提交热卖轮播图
    async submitHot() {
      const arr = this.hotForm.urls.map((url, idx) => ({
        url,
        type: 'post',
        skipUrl: '',
        targetId: this.hotForm.postIds[idx] || ''
      }));
      await this.saveConfig('hotBannerJson', JSON.stringify(arr));
    },
    // 提热卖动轮播图描述
    async submitHotDesc() {
      await this.saveConfig("hotDesc", this.hotDescForm.text);
    },

    // 通用保存方法
    async saveConfig(configKey, value) {
      try {
        await saveAppConfig(configKey, value);
        this.$message.success("保存成功");
      } catch (error) {
        console.error(`保存 ${configKey} 失败`, error);
        this.$message.error("保存失败，请重试");
      }
    },


  }
};
</script>


<style scoped>
.config-section {
  margin-bottom: 20px;
}
</style>
